package org.PDF.PDFUtil
{
	import mx.containers.Canvas;
	import mx.core.Container;
	
	internal class ThmManager
	{
		
		private var _loadedThm:Object;
		private var _destContainer:*;
		private var _thmNameArray:Array = new Array();
		private var _pdfCanvas:Canvas;
		
		public function ThmManager()
		{
		}
		
		public function clean():void
		{
			if (_pdfCanvas != null)
				_pdfCanvas.removeAllChildren();
			(_destContainer as Container).removeChild(_pdfCanvas);	
			this.reset();
		}		
		
		/**
		 * Si on passe thmId à NULL, les libelles sont appliqués à tous les
		 * thèmes chargés
		 */
		public function setThmLib(lib:Object, thmId:String=null):void
		{
			if (_loadedThm == null )
				throw new Error("No Theme loaded");
			else if ( thmId == null )
			{
				for (var i:int = 0; i < _thmNameArray.length ; i++)
					_loadedThm[_thmNameArray[i]].lib = lib;
			}
			else if (_loadedThm[thmId] == null)
				throw new Error("Cannot find theme id : " + thmId);
			else 
				_loadedThm[thmId].lib = lib;
		}
		
		public function get pdfCanvas():Canvas
		{
			return _pdfCanvas;
		}
		
		public function set destContainer(container:*):void
		{
			_destContainer = container;
			_pdfCanvas = new Canvas();
			_pdfCanvas.width = 1;
			_pdfCanvas.height = 1;
			(_destContainer as Container).addChild(_pdfCanvas);			
		}
		
		public function get destContainer():*
		{
			return _destContainer;
		}		
		
		public function addThm(thm:*):void
		{
			if (_loadedThm == null)
				_loadedThm = new Object();
			if (thm.hasOwnProperty("thmId"))
			{
				_loadedThm[thm.thmId] = thm;
				_thmNameArray.push(thm.thmId);
				_pdfCanvas.addChild(thm);
			}
			else
				throw new Error("Please set an Id for you Theme");
		}

		public function getThm(id:String):*
		{
			if (_loadedThm == null )
				throw new Error("No Theme loaded");
			else if (_loadedThm[id] == null)
				throw new Error("Cannot find theme id : " + id);
			else 
				return _loadedThm[id];
		}

		public function reset():void
		{
			if (_loadedThm != null)
			{
				_thmNameArray.splice(0, _thmNameArray.length);
				_loadedThm = null;
			}
		}

	}
}